# -*- encoding : utf-8 -*-
require 'uri/http'
require 'public_suffix'

module Util

  # 截取最后一个symbol后的字符串
  def self.after_last_symbol(string, symbol='/')
    if string and string.index symbol
      string[(string.rindex(symbol) + 1)..string.length]
    else
      string
    end
  end

  # 截取最后一个symbol前的字符串
  def self.before_last_symbol(string, symbol='/')
    if string and string.index symbol
      string[0,string.rindex(symbol)] 
    else
      string
    end
  end

  # 截取第一个symbol前的字符
  def self.before_first_symbol(string, symbol='/')
    if string and string.index symbol
      string[0,string.index(symbol)] 
    else
      string
    end
  end

  # 截取第一个symbol后的字符
  def self.after_first_symbol(string, symbol='/')
    if string and string.index symbol
      string[(string.index(symbol) + 1)..string.length] 
    else
      string
    end
  end

  # 翻转二级域名
  def self.uri_path(uri)
    if uri
      host = self.before_first_symbol uri.host
      domain = PublicSuffix.parse host
      "#{domain.domain}/#{ domain.trd }#{uri.path}"
    else
      nil
    end
  end

end
